<?php
Zend_Loader::loadClass("Application_Ajax_Server_Function");
Zend_Loader::loadClass('Runs');
Zend_Loader::loadClass('Simulations');
Zend_Loader::loadClass('Sites');
Zend_Loader::loadClass('Buildings');
Zend_Loader::loadClass('Zones');

class RunSimulation extends Application_Ajax_Server_Function
{
    protected $_lockfile;

    public function __construct($params = null) {
        $this->_lockfile = "/tmp/" . basename(__FILE__) . ".lock";

        parent::__construct($params);
    }

    public function call() {
		
		foreach ($this->_params as &$param) {
			$param = deep_urldecode($param);
		}

        // Verifica lock
        if (!$this->_lock()) {
            return false;       // FIXME: log "simulation running"
        }

        // Verifica esistenza sim
        $simulations = new Simulations();
        $simulation = $simulations->find($this->_getParam('sim_id', -1));
        if (!$simulation) {
            return false;       // FIXME: log "simulation not found"
        }

        // Verifica esistenza run
        $runs = new Runs();
        $select = $runs->select();
        $select->where("id_simulation = ?", $this->_getParam('sim_id'));
        $run = $runs->fetchRow($select);
        if (!$run) {            // FIXME: log "run record not found"
            return false;
        }
        $run->setFromArray(array(
            'run_date'      => date("Y-m-d H:i:s"),
            'run_status'    => Runs::SIMULATION_READY
        ));
        $run->save();

        // IDF compilation
        $run->run_status = Runs::SIMULATION_IDF_JOB;
        $run->save();

        Zend_Loader::loadClass("Application_IDFCompiler");
        $idfCompiler = new Application_IDFCompiler($this->_getParam('sim_id'));
        try {
            $idfCompiler->compile();
        } catch (Exception $e) {
            // FIXME: log IDF compiler error
            $run->run_status = Runs::SIMULATION_IDF_ERROR;
            $run->save();

            $this->_unlock(true);
            return true;
        }

        $run->run_status = Runs::SIMULATION_IDF_COMPLETE;
        $run->save();

        //$epWrapper = new Application_EnergyPlusWrapper();


        $this->_unlock(true);

        return true;
    }

    protected function _lock($force_unlock = false) {
        if ($this->_unlock($force_unlock)) {
            file_put_contents($this->_lockfile, posix_getpid());
            return true;
        }
        return false;
    }

    protected function _unlock($force = false) {
        if ($force) {
            @unlink($this->_lockfile);
            return true;
        }

        if (!file_exists($this->_lockfile)) {
            return true;
        }

        $pid = file_get_contents($this->_lockfile);

        return
            /*posix_kill($pid, 0) === false
            ||*/ (time() - filemtime($this->_lockfile)) > Runs::SIMULATION_TIMEOUT
        ;
    }


}

function deep_urldecode($var) {
	if (is_array($var)) {
		foreach ($var as &$v) {
			deep_urldecode($v);
		}
	}
	else $var = urldecode($var);
	return $var;
}